package com.doordu.soa.service.web.utils;

import com.github.cage.Cage;
import com.github.cage.IGenerator;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 验证码工具类
 * @author kyler.tang
 *
 */
public class CaptchaUtils {

	/**
	 * 验证码在会话中的key
	 */
	public static final String CAPTCHA_TOKEN = "captcha_token";
	public static final String NEED_CAPTCHA = "need_captcha";

	//private static final String codeChars ="金蝉脱壳百里挑一玉满堂背水战霸王别姬天上人间不吐快海阔空情非得已腹经纶兵临城下春暖花开插翅难逃黄道吉日无双偷换两小猜卧虎藏龙珠光宝气簪缨世族公子绘声影国色香相亲爱八仙过良缘掌明皆大欢喜逍遥法外生财有极乐界自禁愚移山魑魅魍魉九精卫填市蜃楼高流薪尝胆壮志凌云枝叶四家穿针引线忧虑地容三位体落归根见恨晚惊动滔绝濡以沫长死原来如此女娲补皇五帝万箭心木清华窈窕淑破釜沉舟涯角牛郎织倾飘欲福星照妄菲薄永止境学富车饮食男英雄豪杰士塞翁失马灯火石忠报养之覆雨翻六轮回鹰击夜厚德载物亡羊牢时代出入路顺风随遇而安千军郑买履棋逢对手好后会期守株待兔凤凰于飞月圆桃源韬晦画蛇添足青梅竹雪滥竽充数总言没完了欣向荣荏苒差强意先懈可波逐袖旁观群鹿血到底唯我独尊椟还神钟闻负荆请罪成";
	/**
	 * 验证码的位数
	 */
	//public static final int CHAR_NUM = 3;
	private static final CaptchaGenerator cg = new CaptchaGenerator();
	private static final Cage cage = new Cage(null, null,
			null, null, null,
			cg, null);

	public static String drawCaptcha(OutputStream stream) throws IOException{
		String code = genCode();
		cage.draw(code, stream);
		return code;
	}

	public static String genCode(){
		return cg.next();
	}
	/**
	 * 校验验证码,本方法不会删除验证码.请根据业务需要自行删除会话中的验证码
	 * @param code 用户录入的验证码
	 * @param session 当前会话.不能为空.
	 * @return
	 */
	public static Boolean checkCaptcha(String code, HttpSession session) {
		String nc = (String) session.getAttribute(NEED_CAPTCHA);
		String tcode = (String)session.getAttribute(CAPTCHA_TOKEN);
		if (nc != null && nc.equals("1") && tcode != null) {
			boolean flag = tcode.equalsIgnoreCase(code);
			//验证成功后删除验证码.
			if (flag) {
				session.removeAttribute(NEED_CAPTCHA);
			}
			return flag;
		} else {
			return true;
		}
	}
}

class CaptchaGenerator implements IGenerator<String>{
	/**
	 * 验证码的位数
	 */
	public static final int CHAR_NUM = 4;
	private static final String codeChars = "356789ADEFGHJKLMNPQRSTUWXY356789adeghjkmnpqrstuwxy356789";
	
	@Override
	public String next() {
		StringBuilder code = new StringBuilder();
		for(int i=0;i<CHAR_NUM;i++){
			char c = codeChars.charAt((int)Math.floor(Math.random()*codeChars.length()));
			code.append(c);
		}
		return code.toString();
	}
	
}
